package com.jader.myviews;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jader.activities.Seller;
import com.jader.beans.Goods;
import com.jader.db.MyData;
import com.jader.util.JaderApplication;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ImageView.ScaleType;

public class SlideShowView extends FrameLayout {
	// 使用universal-image-loader插件读取网络图片，需要工程导入universal-image-loader-1.8.6-with-sources.jar
	private final static int IMAGE_COUNT = 5;
	// 自动轮播的时间间隔
	@SuppressWarnings("unused")
	private final static int TIME_INTERVAL = 5;
	// 自动轮播启用开关
	private final static boolean isAutoPlay = true;
	// 自定义轮播图的资源
	private String[] imageUrls;
	// 放轮播图片的ImageView 的list
	private List<ImageView> imageViewsList;
	// 放圆点的View的list
	private List<View> dotViewsList;
	// 轮播图片
	private ViewPager viewPager;
	// 当前轮播页
	private int currentItem = 0;
	// 定时任务
	private ScheduledExecutorService scheduledExecutorService;

	private Context context;
	private List<Goods> list = new ArrayList<Goods>();
	private SQLiteDatabase sqLiteDatabase;
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			viewPager.setCurrentItem(currentItem);
		};

	};

	public SlideShowView(Context context) {
		this(context, null);

	}

	public SlideShowView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);

	}

	public SlideShowView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		this.context = context;
		HttpUtils httpUtils = new HttpUtils();
		httpUtils.send(HttpMethod.GET, JaderApplication.getIP()
				+ "/Jader/client?type=11&sellerid=1",

		/*
		 * httpUtils.send(HttpMethod.GET,
		 * JaderApplication.getIP()+"/Jader/client?" +
		 * "type="+JaderApplication.SEARCH_PICTURE+ "+&sellerid=1",
		 */
		new RequestCallBack<String>() {

			@Override
			public void onFailure(HttpException arg0, String arg1) {
				sqLiteDatabase = JaderApplication.getSqLiteDatabase();
				String sql = "select * from " + MyData.LUNBOYUPIC_TABLENAME;
				Cursor cursor = sqLiteDatabase.rawQuery(sql, null);
				// list.clear();
				while (cursor.moveToNext()) {
					int i = 0;
					if (i >= 4) {
						break;
					}
					int msg = cursor.getInt(0);
					String picture = cursor.getString(1);
					list.add(new Goods(null,msg, 0, null, 0, null, null, picture, 0,
							0));
					i++;

				}

				sqLiteDatabase.close();
				initGoods();
			}

			@Override
			public void onSuccess(ResponseInfo<String> arg0) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<Goods>>() {
				}.getType();
				list = gson.fromJson(arg0.result, type);
				initGoods();
				sqLiteDatabase = JaderApplication.getSqLiteDatabase();
				String delete = "delete from " + MyData.LUNBOYUPIC_TABLENAME;
				sqLiteDatabase.execSQL(delete);
				sqLiteDatabase.close();
				for (int i = 0; i < 4; i++) {
					if (i < list.size()) {
						Goods good = list.get(i);
						sqLiteDatabase = JaderApplication.getSqLiteDatabase();
						String sql = "insert into "
								+ MyData.LUNBOYUPIC_TABLENAME + " values(?,?)";
						String[] texts = { good.getGoodsid() + "",
								good.getPicture() };
						if (texts != null) {
							sqLiteDatabase.execSQL(sql, texts);
						}
						sqLiteDatabase.close();
					}
				}

			}
		});
	}

	private void initGoods() {

		initData();
		// new GetListTask().execute("");
		if (list.size() >= 4) {
			imageUrls = new String[] {
					JaderApplication.getIP()+"/Jader"+ list.get(0).getPicture(),
					JaderApplication.getIP()+"/Jader" + list.get(1).getPicture(),
					JaderApplication.getIP() +"/Jader"+ list.get(2).getPicture(),
					JaderApplication.getIP() +"/Jader"+ list.get(3).getPicture() };
		}
		initUI(context);
		if (isAutoPlay) {
			startPlay();
		}

	}

	private void startPlay() {
		// 开始播放
		scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
		scheduledExecutorService.scheduleAtFixedRate(new SlideShowTask(), 1, 4,
				TimeUnit.SECONDS);
	}

	// 停止播放
	// private void stopPlay() {
	// scheduledExecutorService.shutdown();
	// }

	private void initData() {
		imageViewsList = new ArrayList<ImageView>();
		dotViewsList = new ArrayList<View>();

	}

	/**
	 * 初始化Views等UI
	 */
	private void initUI(Context context) {
		if (imageUrls == null || imageUrls.length == 0)
			return;
		LayoutInflater.from(context).inflate(R.layout.layout_slideshow, this,
				true);

		LinearLayout dotLayout = (LinearLayout) findViewById(R.id.dotLayout);
		dotLayout.removeAllViews();

		// 热点个数与图片特殊相等
		for (int i = 0; i < imageUrls.length; i++) {
			ImageView view = new ImageView(context);
			view.setTag(imageUrls[i]);
			if (i == 0)// 给一个默认图
				view.setBackgroundResource(R.drawable.tu1);
			view.setScaleType(ScaleType.FIT_XY);
			imageViewsList.add(view);

			ImageView dotView = new ImageView(context);
			LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
					LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			params.leftMargin = 4;
			params.rightMargin = 4;
			dotLayout.addView(dotView, params);
			dotViewsList.add(dotView);
		}

		viewPager = (ViewPager) findViewById(R.id.viewPager);
		viewPager.setFocusable(true);
		viewPager.setAdapter(new MyPagerAdapter());
		viewPager.setOnPageChangeListener(new MyPageChangeListener());
	}

	private class MyPagerAdapter extends PagerAdapter {

		@Override
		public void destroyItem(View container, int position, Object object) {
			((ViewPager) container).removeView(imageViewsList.get(position));
		}

		// 进行页面跳转

		@Override
		public Object instantiateItem(ViewGroup container, int position) {

			// 点击轮播图片跳转到具体商品的详情界面
			final Intent intent = new Intent(getContext(), Seller.class);
			final Bundle bundle = new Bundle();
			switch (position) {
			case 0:
				imageViewsList.get(0).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {
								bundle.putSerializable("goods", list.get(0));
								intent.putExtras(bundle);
								getContext().startActivity(intent);
							}
						});

				break;
			case 1:
				imageViewsList.get(1).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {
								bundle.putSerializable("goods", list.get(1));
								intent.putExtras(bundle);
								getContext().startActivity(intent);
							}
						});
				break;
			case 2:
				imageViewsList.get(2).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {
								bundle.putSerializable("goods", list.get(2));
								intent.putExtras(bundle);
								getContext().startActivity(intent);
							}
						});
				break;
			case 3:
				imageViewsList.get(3).setOnClickListener(
						new View.OnClickListener() {

							@Override
							public void onClick(View arg0) {
								bundle.putSerializable("goods", list.get(3));
								intent.putExtras(bundle);
								getContext().startActivity(intent);
							}
						});
				break;
			default:

				break;
			}

			return super.instantiateItem(container, position);
		}

		@Override
		public Object instantiateItem(View container, int position) {

			ImageView imageView = imageViewsList.get(position);
			JaderApplication.getBitmapUtils().display(imageView,
					imageView.getTag() + "");
			((ViewPager) container).addView(imageViewsList.get(position));
			return imageViewsList.get(position);
		}

		@Override
		public int getCount() {
			return imageViewsList.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {

		}

		@Override
		public void finishUpdate(View arg0) {

		}

	}

	private class MyPageChangeListener implements OnPageChangeListener {

		boolean isAutoPlay = false;

		@Override
		public void onPageScrollStateChanged(int arg0) {
			switch (arg0) {
			case 1:// 手势滑动，空闲中
				isAutoPlay = false;
				break;
			case 2:// 界面切换中
				isAutoPlay = true;
				break;
			case 0:// 滑动结束，即切换完毕或者加载完毕
					// 当前为最后一张，此时从右向左滑，则切换到第一张
				if (viewPager.getCurrentItem() == viewPager.getAdapter()
						.getCount() - 1 && !isAutoPlay) {
					viewPager.setCurrentItem(0);
				}
				// 当前为第一张，此时从左向右滑，则切换到最后一张
				else if (viewPager.getCurrentItem() == 0 && !isAutoPlay) {
					viewPager
							.setCurrentItem(viewPager.getAdapter().getCount() - 1);
				}
				break;
			}
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int pos) {

			currentItem = pos;
			for (int i = 0; i < dotViewsList.size(); i++) {
				if (i == pos) {
					((View) dotViewsList.get(pos))
							.setBackgroundResource(R.drawable.dot_focus);
				} else {
					((View) dotViewsList.get(i))
							.setBackgroundResource(R.drawable.dot_blur);
				}
			}
		}

	}

	private class SlideShowTask implements Runnable {

		@Override
		public void run() {
			synchronized (viewPager) {
				currentItem = (currentItem + 1) % imageViewsList.size();
				handler.obtainMessage().sendToTarget();
			}
		}

	}

	@SuppressWarnings("unused")
	private void destoryBitmaps() {

		for (int i = 0; i < IMAGE_COUNT; i++) {
			ImageView imageView = imageViewsList.get(i);
			Drawable drawable = imageView.getDrawable();
			if (drawable != null) {
				// 解除drawable对view的引用
				drawable.setCallback(null);
			}
		}
	}

}
